using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.Serialization;
using System.Reflection;

using WeatherRouter;
using WeatherRouter.Model;

namespace WeatherRouter.Dispatcher
{    
    public class Packet
    {
        private string _item;        
        
        public string Item
        {
            get { return _item; }
            set { _item = value; }
        }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public Packet()
        {            
        }

        public void LoadDocument(Feed feed, DaySpan daySpan, bool transliterate)
        {
            XslCompiledTransform xsl = null;
            MemoryStream packetStream = null;
            StreamReader sr = null;

            try
            {   
                xsl = new XslCompiledTransform();
                packetStream = new MemoryStream();

                // We are setting stylesheet as trusted, so we can use external vocabulary to provide global support
                xsl.Load(Cache.Instance.CacheFolder + @"\" + feed.ItemSchema, XsltSettings.TrustedXslt, new XmlUrlResolver());                
                xsl.Transform(daySpan.Item.CreateNavigator(), null, new XmlTextWriter(packetStream, Encoding.GetEncoding(1251)));

                // Read packet to string.
                packetStream.Seek(0, SeekOrigin.Begin);
                sr = new StreamReader(packetStream, Encoding.GetEncoding(1251));
                _item = sr.ReadToEnd();

                if (transliterate)
                {
                    _item = Translit.Instance.Encode(_item);
                }
            }
            catch (IOException ex)
            {
                LogManager.Error("Could not parse packet for feed " + feed.Name + " " + ex.ToString());
            }
            finally
            {                
                if (packetStream != null)
                {
                    packetStream.Close();
                }
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }

        /// <summary>
        /// Emits packet content.
        /// </summary>
        /// <returns>Packet content in textual form.</returns>
        public override string ToString()
        {
            return _item;
        }
    }
}